#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "../include/hashtable.h"
#include "../include/linkedlist.h"
#include "../include/constants.h"
#include "../include/errors.h"


int initialize_hashtable(hashtable *ht)
{
    int i;
    for( i=0; i<MAXNODE; i++)
        ht->Table[i]=NULL;
    return 0;
}

//--------calculation of key value

int hashfunctn(char c)
{
    int value= (int)c;
    if((value>=65) && (value<=90))
        return ((value%65)+26);
    else if ((value>=97) && (value<=122))
        return (value%97);
    else if(((value>=32) && (value<=46))||((value>=48) && (value<=64))||
            ((value>=91) && (value<=96))||((value>=123) && (value<=126)))
        return MAXNODE-1;
    else
        return MAXNODE;
}

//hashtable insert------------------------------
int insert_hashtable(hashtable *ht,fdesc *fd1)
{

    char c=fd1->f_name[0];
    char name[CHARSIZE];
    strcpy(name,fd1->f_name);
    int key=hashfunctn(c);
    ht->Table[key]=list_insert_end(ht->Table[key],name,fd1);
    return 1;
}





// search  a file
l_node* search_hashtable(hashtable *ht, char* filename)
{
    int key;
    l_node *start;
    char c = filename[0];
    key = hashfunctn(c);
    start = ht->Table[key];
    return list_search_strkey(start, filename);
}

l_node* search_pre_hashtable(hashtable *ht, char* filename)
{
    int key;
    l_node *start;
    char c = filename[0];
    key = hashfunctn(c);
    start = ht->Table[key];
    return list_search_prefix(start, filename);

}


int delete_hashtable(hashtable *ht, fdesc *fd1)
{
    int key;
    char name[CHARSIZE];
    strcpy(name,fd1->f_name);
    char c = fd1->f_name[0];
    key = hashfunctn(c);
    ht->Table[key] = list_delete_node(ht->Table[key],fd1);
    if(ht->Table[key]==NULL)
        return 1;
    return 1;
}


void print_hashtable(hashtable *ht)
{
    int i;
    for (i = 0; i < MAXNODE; i++)
    {
        printf("\nprint %d -> ", i);
        if (ht->Table[i] != NULL )
        {
            print_list(ht->Table[i]);
        }
        printf("\n");
    }
}
